package com.restaurant.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.restaurant.dto.PieDto;
import com.restaurant.dto.TotalDto;
import com.restaurant.dto.TransportDto;
import com.restaurant.entity.*;
import com.restaurant.mapper.CompanyMapper;
import com.restaurant.mapper.GoodMapper;
import com.restaurant.mapper.UserMapper;
import com.restaurant.mapper.material.ProductMapper;
import com.restaurant.mapper.material.ProductRecordMapper;
import com.restaurant.mapper.transport.TransportRecordMapper;
import com.restaurant.result.Result;
import com.restaurant.service.CompanyService;
import com.restaurant.service.GoodService;
import com.restaurant.service.impl.material.ProductRecordServiceImpl;
import com.restaurant.service.material.ProduceRecordService;
import com.restaurant.service.material.ProductService;
import com.restaurant.service.transport.TransportRecordService;
import com.restaurant.service.transport.TransportService;
import com.restaurant.vo.product.ProductQueryVo;
import com.restaurant.vo.product.ProductRecordQueryVo;
import com.restaurant.vo.product.ProductRecordVo;
import com.restaurant.vo.transport.TransportQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.fisco.bcos.sdk.v3.transaction.model.exception.ContractException;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/manage")
public class ManageController {
    @Resource
    private ProductService productService;

    @Resource
    private ProduceRecordService productRecordService;

    @Resource
    private CompanyService companyService;

    @Resource
    private TransportService transportService;

    @Resource
    private TransportRecordService transportRecordService;

    @Resource
    private CompanyMapper companyMapper;

    @Resource
    private GoodMapper goodMapper;

    @Resource
    private UserMapper userMapper;
    @Resource
    private ProductRecordMapper productRecordMapper;

    @Resource
    private TransportRecordMapper transportRecordMapper;

    /**
     * 农作物展示
     *
     * @param productQueryVo
     * @return
     */
    @PostMapping("/page")
    public Result<Page> pageProduct(@RequestBody ProductQueryVo productQueryVo, HttpServletRequest request) {

        String name = productQueryVo.getName();
        String type = productQueryVo.getType();
        Integer page = productQueryVo.getPage();
        Integer limit = productQueryVo.getLimit();

        Page<Product> pageInfo = new Page(page, limit);
        User user = (User) request.getSession().getAttribute("user");
        if (user.getId() == null) {
            return Result.error("请先登录");
        }

        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper();
//        queryWrapper.eq(Product::getUserId,user.getId());
        queryWrapper.like(StringUtils.isNotEmpty(name), Product::getName, name);
        queryWrapper.like(StringUtils.isNotEmpty(type), Product::getType, type);
        queryWrapper.orderByDesc(Product::getProductDate);

        productService.page(pageInfo, queryWrapper);

        return Result.success(pageInfo);

    }

    /**
     * 公司展示
     *
     * @param productQueryVo
     * @return
     */
    @PostMapping("/company")
    public Result<Page> pageCompany(@RequestBody ProductQueryVo productQueryVo, HttpServletRequest request) {
        String name = productQueryVo.getName();
        String type = productQueryVo.getType();
        Integer page = productQueryVo.getPage();
        Integer limit = productQueryVo.getLimit();

        Page<Company> pageInfo = new Page(page, limit);
        User user = (User) request.getSession().getAttribute("user");
        if (user.getId() == null) {
            return Result.error("请先登录");
        }

        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper();
//        queryWrapper.eq(Product::getUserId,user.getId());
        queryWrapper.like(StringUtils.isNotEmpty(name), Company::getName, name);
        queryWrapper.like(StringUtils.isNotEmpty(type), Company::getType, type);
//        queryWrapper.orderByDesc(Company::getProductDate);

        companyService.page(pageInfo, queryWrapper);

        return Result.success(pageInfo);

    }

    /**
     * 运输员运输工作展示
     *
     * @param transportQueryVo
     * @param request
     * @return
     */
    @PostMapping("/transport")
    public Result transportPage(@RequestBody TransportQueryVo transportQueryVo, HttpServletRequest request) {
        Long id = transportQueryVo.getId();
        Integer status = transportQueryVo.getStatus();
        Integer page = transportQueryVo.getPage();
        Integer limit = transportQueryVo.getLimit();

        Page<Transport> pageInfo = new Page(page, limit);
        Page<TransportDto> transportDtoPage = new Page<>();

        User user = (User) request.getSession().getAttribute("user");
        if (user.getId() == null) {
            return Result.error("请先登录");
        }

        LambdaQueryWrapper<Transport> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(id != null, Transport::getProductId, id);
        queryWrapper.eq(status != null, Transport::getStatus, status);
        queryWrapper.orderByDesc(Transport::getRecordTime);

        transportService.page(pageInfo, queryWrapper);

        BeanUtils.copyProperties(pageInfo, transportDtoPage);

        return Result.success(transportDtoPage);
    }

    @PostMapping("/temp")
    public Result temp() {
        companyMapper.updatea(); // 清空 count 列

        List<ProductRecord> list = productRecordService.list();
        for (int i = 0; i < list.size(); i++) {
            companyMapper.updateCompanyCount(list.get(i).getUserId());
        }

        List<TransportRecord> list1 = transportRecordService.list();
        for (int i = 0; i < list1.size(); i++) {
            companyMapper.updateCompanyCount2(list.get(i).getUserId());
        }

        return Result.success();
    }

    /**
     * pie图
     *
     * @return
     */
    @PostMapping("/pie")
    public Result<PieDto> piePicture() {
        PieDto pieDto = new PieDto();
        pieDto.setFruits(goodMapper.countFruits());
        pieDto.setLegumes(goodMapper.countLegumes());
        pieDto.setGrains(goodMapper.countGrains());
        pieDto.setVegetables(goodMapper.countVegetables());

        return Result.success(pieDto);
    }

    @PostMapping("/total")
    public Result<TotalDto> total() {
        TotalDto totalDto = new TotalDto();
        QueryWrapper<User> wrapper1 = new QueryWrapper<>();
        totalDto.setExistingUsers(userMapper.selectCount(wrapper1));
        QueryWrapper<Good> wrapper2 = new QueryWrapper<>();
        totalDto.setAgriculturalProductCount(goodMapper.selectCount(wrapper2));

        QueryWrapper<ProductRecord> wrapper3 = new QueryWrapper<>();
        QueryWrapper<TransportRecord> wrapper4 = new QueryWrapper<>();
        totalDto.setTransactionCount(productRecordMapper.selectCount(wrapper3) + transportRecordMapper.selectCount(wrapper4));

        LocalDateTime startOfToday = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime endOfToday = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);

        // 设置注册时间范围为今天
        wrapper3.between("record_time", startOfToday, endOfToday);
        wrapper4.between("record_time", startOfToday, endOfToday);
        totalDto.setTodayTransactions(productRecordMapper.selectCount(wrapper3) + transportRecordMapper.selectCount(wrapper4));

        return Result.success(totalDto);
    }
}
